<?php
// +----------------------------------------------------------------------
// | Description: 商城接口
// +----------------------------------------------------------------------
// | Author: zl
// +----------------------------------------------------------------------

namespace app\crm\controller;
use app\admin\controller\ApiCommon;
use think\response\Json;
use think\facade\Db;
use Kingdee\Kingdee;
use app\Request;
use think\Env;

class ProductItem  extends ApiCommon
{
     /**
     * 获取列表
     */
    public function getProductItem(Request $request)
    {
        $param = $request->param();
        $page = $param['page']??1;
        $pagesize = $param['pagesize']??10;
        $is_export = $param['is_export'] ?? 0;

        $where = [];

        // 基础查询条件
        if (!empty($param['name']))
        {
            $where[] = ['pi.name', 'like', '%' . $param['name'] . '%'];
        }
        if (!empty($param['status']))
        {
            $where[] = ['pi.status', '=', $param['status']];
        }
        // 日期范围处理
        if (!empty($param['start']) || !empty($param['end']))
        {
            $start = !empty($param['start'])  ? strtotime($param['start'] . ' 00:00:00')  : strtotime(date('Y-m-d 00:00:00'));
            $end = !empty($param['end'])  ? strtotime($param['end'] . ' 23:59:59')  : strtotime(date('Y-m-d 23:59:59'));
            $where[] = ['pi.create_time', 'between', [$start, $end]];
        }

        // 类目级别查询
        if (!empty($param['level']) && !empty($param['type_id']))
        {
            $levelFieldMap = [
                1 => 'type_one',
                2 => 'type_two',
                3 => 'type_three',
            ];
            $field = $levelFieldMap[$param['level']] ?? null;
            if ($field)
            {
                $where[] = ['pi.'.$field, '=', $param['type_id']];
            }
        }

        // 构建查询
        $query = Db::name('product_item')
            ->alias('pi')
            // 关联一级类目
            ->leftJoin('xy_item_type t1', 'pi.type_one = t1.id')
            // 关联二级类目
            ->leftJoin('xy_item_type t2', 'pi.type_two = t2.id')
            // 关联三级类目
            ->leftJoin('xy_item_type t3', 'pi.type_three = t3.id')
            // 关联创建人
            ->leftJoin('xy_admin_user cu', 'pi.creator_id = cu.id')
            // 关联修改人
            ->leftJoin('xy_admin_user mu', 'pi.modifier_id = mu.id')
            // 选择基础字段
            ->field('pi.*')
            // 选择类目标题
            ->field('t1.name as type_one_name, t2.name as type_two_name, t3.name as type_three_name')
            // 选择创建人和修改人姓名
            ->field('cu.realname as creator_name, mu.realname as modifier_name')
            ->order('pi.id', 'desc');

        // 添加查询条件
        if (!empty($where))
        {
            $query->where($where);
        }

        if($is_export == 1)
        {

            $result = $query->select()->toArray();

            $result = json_decode(json_encode($result),1);

            // 处理关联门店和JSON字段
            foreach ($result as &$item)
            {
                // 处理product_info JSON字段
                $item['product_info'] = json_decode($item['product_info'], true) ?: [];

                // 处理时间戳字段
                $item['create_time'] = ($item['create_time'] != 0) ? (date('Y-m-d', $item['create_time'])?? '') : "";
                $item['update_time'] = ($item['update_time'] != 0) ? (date('Y-m-d', $item['update_time'])?? '') : "";
            }
            unset($item); // 避免引用问题


            // 展开 product_info 数据
            $expandedResult = [];
            foreach ($result as $item)
            {
                $productInfo = $item['product_info'] ?: [];

                // 如果没有子项，保留原数据
                if (empty($productInfo))
                {
                    $expandedResult[] = $item;
                    continue;
                }

                // 为每个 product_info 创建新记录
                foreach ($productInfo as $info)
                {
                    $newItem = $item; // 复制主记录

                    // 合并子项数据，使用不同的字段名避免冲突
                    $newItem['goods_id'] = $info['id'] ?? null;
                    $newItem['goods_name'] = $info['name'] ?? null;
                    $newItem['kingdee_code'] = $info['kingdee_code'] ?? null;
                    $newItem['goods_price'] = $info['goods_price'] ?? null;
                    $newItem['spec_name'] = $info['spec_name'] ?? null;
                    $newItem['goods_number'] = $info['number'] ?? null;
                    $newItem['unit_name'] = $info['unit_name'] ?? null;
                    $newItem['package_price'] = $info['package_price'] ?? null;
                    $newItem['selling_price'] = $info['selling_price'] ?? null;

                    // 移除原始的 product_info 字段
                    unset($newItem['product_info']);

                    $expandedResult[] = $newItem;
                }
            }

            // 使用展开后的结果
            $result = $expandedResult;

            $excelName = "品项列表";

            $callName = [
                'name' => '品项名称',
                'number' => '使用次数',
                'type_one_name' => '一级类目',
                'type_two_name' => '二级类目',
                'type_three_name' => '三级类目',
                'price' => '组合价格',
                'goods_name' => '产品名称',
                'kingdee_code' =>  '金蝶编码',
                'goods_price' => '产品单价',
                'goods_number' => '产品数量',
                'selling_price' => '产品组合价格',
                'package_price' => '组合销售价格',
                'spec_name' => '产品规格',
                'unit_name' => '产品单位',
                'creator_name' => '创建人',
                'create_time' => '创建时间',
            ];

            $downUrl = exportExcelData($excelName,$callName,$result,'xlsx',1);
            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
        }else
        {
             // 执行查询
            $result = $query->paginate([
                'list_rows'=>$pagesize,
                'page'=>$page,
                'query'=>request()->param()
            ]);

            $result = json_decode(json_encode($result),1);

            // 处理关联门店和JSON字段
            foreach ($result['data'] as &$item)
            {
                // 处理product_info JSON字段
                $item['product_info'] = json_decode($item['product_info'], true) ?: [];

                // 处理时间戳字段
                $item['create_time'] = ($item['create_time'] != 0) ? (date('Y-m-d', $item['create_time'])?? '') : "";
                $item['update_time'] = ($item['update_time'] != 0) ? (date('Y-m-d', $item['update_time'])?? '') : "";
            }
            unset($item); // 避免引用问题
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $result]);
        }
        exit;
    }


    /**
     * 添加品项
     */
    public function addProductItem(Request $request)
    {
        $param = $request->param();
        $insert['create_time'] = time();

         // 验证必填字段
        $requiredFields = [
            'name' => '品项名称',
            'number' => '次数',
            'type_one' => '一级类目',
            'type_two' => '二级类目',
            'type_three' => '三级类目',
            'price' => '组合价格',
            'status' => '状态',
            'product_info' => '商品信息',
            'creator_id' => '创建人',
        ];
        foreach ($requiredFields as $field => $message)
        {
            if (empty($param[$field]))
            {
                return json(['code' => 0, 'msg' => "{$message}不能为空"]);
            }
        }

        // 检查同等级下是否存在同名分类
        $exists = Db::name('product_item')->where('name', $param['name'])->count();
        if ($exists)
        {
            return json(['code' => 0, 'msg' => '已存在同名品项']);
        }

        //拼接数据
        $insert['name'] = $param['name'];
        $insert['number'] = $param['number'];
        $insert['type_one'] = $param['type_one'];
        $insert['type_two'] = $param['type_two'];
        $insert['type_three'] = $param['type_three'];
        $insert['price'] = $param['price'];
        $insert['status'] = $param['status'];
        $insert['creator_id'] = $param['creator_id'];
        $insert['product_ids'] = $param['product_ids'];
        $insert['mini_ids'] = $param['mini_ids'];
        // 计算并比较package_price
        $insert['product_info'] = $this->calculateCombinedPrices($param['price'], json_decode($param['product_info'],1));
        $insert['product_info'] = json_encode($insert['product_info']);

        $id = Db::name('product_item')->insertGetId($insert);

        if ($id)
        {
            return json(['code' => 200, 'msg' => '添加成功', 'data' => ['id' => $id]]);
        }else
        {
            return json(['code' => 0, 'msg' => '添加失败']);
        }
    }




    /**
     * 修改品项
     *
     * 品项可以修改的内容：
     * 品项名称可以修改（修改的新名称必须是系统之前没有添加过的才可以）；
     * 品项次数和品项金额 可以修改；品项是否禁用可以修改；适配门店可以修改；
     * 该项目没有被使用之前 是可以新增对应的产品明细或减少产品 ，如果该品项已经被开单是不能再进行修改这个产品信息；
     */
    public function editProductItem(Request $request)
    {
        $param = $request->param();
        $param['update_time'] = time();

        $id = $param['id'];
        // 验证ID
        if (empty($id))
        {
            return json(['code' => 0, 'msg' => 'ID不能为空']);
        }

        // 检查品项是否存在
        $item = Db::name('product_item')->where('id', $id)->find();
        if (!$item)
        {
            return json(['code' => 0, 'msg' => '品项不存在']);
        }

        // 检查同等级下是否存在同名分类（排除自身）
        $exists = Db::name('product_item')->where('name', $param['name'])->where('id', '<>', $id)->count();
        if ($exists)
        {
            return json(['code' => 0, 'msg' => '已存在同名品项']);
        }

        // 判断品项是否已经开单
        if (!empty($param['product_info']))
        {
            // $check = Db::name('order')->where('id', $id)->count();
            $check = 0;
            if ($check == 0)
            {
                // 获取原始品项数据（假设$item已经正确获取）
                $originalProductInfo = json_decode($item['product_info'], true);
                $newProductInfo = json_decode($param['product_info'], true);

                // 判断提交的数据和原始数据是否不同
                if ($newProductInfo != $originalProductInfo) {
                    // 数据有变化，重新计算package_price
                    $calculatedProductInfo = $this->calculateCombinedPrices($param['price'], $newProductInfo);
                    $param['product_info'] = json_encode($calculatedProductInfo);
                }
            }else
            {
                // 已开单，不允许修改product_info
                unset($param['product_info']);
            }
        }

        // 执行更新
        $result = Db::name('product_item')->where('id', $param['id'])->update($param);

        if ($result !== false)
        {
            return json(['code' => 200, 'msg' => '修改成功']);
        }else
        {
            return json(['code' => 0, 'msg' => '修改失败']);
        }
    }




    /**
     * 计算组合销售价格并添加到产品信息中
     * @param float $price 品项组合价格
     * @param array $product_info 产品数组，每个元素包含 'goods_price' (单价) 和 'number' (数量)
     * @return array 更新后的产品信息，包含 'package_price' 键
     */
    public function calculateCombinedPrices($price, $product_info)
    {
        $totalOriginal = '0';
        $productCount = count($product_info);
        $sumPrevious = '0';
        $calculatedPrices = [];

        // 计算全部产品原价总和
        foreach ($product_info as $product)
        {
            $original = bcmul($product['goods_price'], $product['number'], 2);
            $totalOriginal = bcadd($totalOriginal, $original, 2);
        }

        // 计算每个产品的组合销售价格
        for ($i = 0; $i < $productCount; $i++)
        {
            $product = $product_info[$i];
            $original = bcmul($product['goods_price'], $product['number'], 2);

            if ($i < $productCount - 1)
            {
                // 非最后一个产品
                if (bccomp($totalOriginal, '0', 2) === 0) {
                    $ratio = '0';
                } else {
                    $ratio = bcdiv($price, $totalOriginal, 10);
                }
                $priceValue = bcmul($ratio, $original, 10);
                $roundedPrice = round($priceValue);
                $calculatedPrices[$i] = $roundedPrice;
                $sumPrevious = bcadd($sumPrevious, (string)$roundedPrice, 2);
            }else
            {
                // 最后一个产品
                $lastPrice = bcsub($price, $sumPrevious, 2);
                $calculatedPrices[$i] = round($lastPrice);
            }
        }

        // 比较并替换package_price
        foreach ($product_info as $index => &$product)
        {
            if (isset($product['package_price']))
            {
                if ((int)$product['package_price'] !== $calculatedPrices[$index])
                {
                    $product['package_price'] = $calculatedPrices[$index];
                }
            }else
            {
                $product['package_price'] = $calculatedPrices[$index];
            }
        }
        unset($product); // 避免后续引用问题

        return $product_info;
    }




    /**
     * 递归构建树形结构
     */
    private function buildTree($items, $pid = 0)
    {
        $tree = [];
        foreach ($items as $item) {
            if ($item['pid'] == $pid) {
                // 递归查找子节点
                $children = $this->buildTree($items, $item['id']);
                if (!empty($children)) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }




    /**
     * 获取商品
     */
    public function getGoodsList(Request $request)
    {
        $param = $request->param();

        // 使用闭包创建UNION查询
        $result = Db::name('shop_goods')
            ->field('id, name, kingdee_code, goods_price, unit_name, spec_name, "goods" as type')
            ->where('is_project', 'in', '3,4')
            ->where('status', 1)
            ->where('delete_time', 0)
            ->union(function ($query) use ($param) {
                $query->name('shop_goods_mini')
                    ->field('id, name, kingdee_code, goods_price, unit_name, mini_unit as spec_name, "mini" as type')
                    ->where('status', 1)
                    ->whereNull('delete_time');
                    
                if (!empty($param['search'])) {
                    $searchLike = "%{$param['search']}%";
                    $query->where(function ($q) use ($searchLike) {
                        $q->where('kingdee_code', 'like', $searchLike)
                          ->whereOr('name', 'like', $searchLike);
                    });
                }
            }, true)
            ->when(!empty($param['search']), function ($query) use ($param) {
                $searchLike = "%{$param['search']}%";
                $query->where(function ($q) use ($searchLike) {
                    $q->where('kingdee_code', 'like', $searchLike)
                      ->whereOr('name', 'like', $searchLike);
                });
            })
            // 添加排序规则：先按type排序（goods在前），再按id排序
            ->order('type', 'asc')
            ->order('id', 'asc')
            ->select()
            ->toArray();
        
        // 重命名字段：顺序索引作为id，原始id作为index
        // $indexedResult = [];
        // foreach ($result as $key => $item) {
        //     $newItem = [
        //         'id' => $key + 1,  // 新的id字段：顺序索引（从1开始）
        //         'index' => $item['id'],  // 原始id字段重命名为index
        //         'name' => $item['name'],
        //         'kingdee_code' => $item['kingdee_code'],
        //         'goods_price' => $item['goods_price'],
        //         'unit_name' => $item['unit_name'],
        //         'spec_name' => $item['spec_name'],
        //         'type' => $item['type']
        //     ];
        //     $indexedResult[] = $newItem;
        // }
        
        return json(['code' => 200, 'data' => $result]);
    }



   /**
     * 获取店铺
     */
    public function getShopList(Request $request)
    {
        $param = $request->param();
        // 构建查询
        $result = Db::name('shop')
            ->field('shop_id, shop_name, market_id, market_name')
            ->where('status', 1)
            ->select()
            ->toArray();

        foreach ($result as $shop)
        {
            $marketId = $shop['market_id'];
            if (!isset($groupedShops[$marketId]))
            {
                $groupedShops[$marketId] = [
                    'id' => $marketId,
                    'shop_name' => $shop['market_name'],
                    'children' => []
                ];
            }
            $groupedShops[$marketId]['children'][] = [
                'shop_id' => $shop['shop_id'],
                'shop_name' => $shop['shop_name']
            ];
        }

        return json(['code' => 200, 'data' => array_values($groupedShops)]);
    }


}
